package com.nti56.springboot;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.unit.DataSize;
import org.springframework.util.unit.DataUnit;
import org.springframework.web.WebApplicationInitializer;

import javax.servlet.MultipartConfigElement;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
该注解指定项目为springboot，由此类当作程序入口
自动装配 web 依赖的环境

**/
@EnableTransactionManagement
@SpringBootApplication
@ServletComponentScan
@Configuration
@EnableScheduling
public class SpringBootApp extends SpringBootServletInitializer implements WebApplicationInitializer{
	
	@Autowired
	private Environment env;
	
	/**
	 * 指定fastjson 替换jackson
	 * 否则 jackson和  lombok.Data 配合使用  解析JSON 有BUG
	 * @return
	 */
	@Bean
    public HttpMessageConverters fastJsonHttpMessageConverters(){
        //1.需要定义一个convert转换消息的对象;
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        //2:添加fastJson的配置信息;
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        /**
         * TODO 第一个SerializerFeature.PrettyFormat可以省略，毕竟这会造成额外的内存消耗和流量，第二个是用来指定当属性值为null是是否输出：pro:null
　　　　　 * SerializerFeature.SkipTransientField
		 解决faston 循环引用问题，例如$.rows[0].repertotyEnd 问题
		 SerializerFeature.DisableCircularReferenceDetect
         */
        fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue,
        									 SerializerFeature.DisableCircularReferenceDetect);
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        fastJsonConfig.setCharset(Charset.forName("UTF-8"));
        //3处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<MediaType>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        //4.在convert中添加配置信息.
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        HttpMessageConverter<?> converter = fastJsonHttpMessageConverter;
        return new HttpMessageConverters(converter);
    }
	
	//springBoot接收date类型参数转换
	@Bean
    public Converter<String, Date> addNewConvert() {
        return new Converter<String, Date>() {
            @Override
            public Date convert(String source) {
                SimpleDateFormat sdf = null;
                Date date = null;
                try {
                	if(!source.isEmpty()) {
                	  if (source.length() < 10) {
                            sdf = new SimpleDateFormat("HH:mm");
                      }
                	  if (source.length() == 10) {
                          sdf = new SimpleDateFormat("yyyy-MM-dd");
                      }
                      if (source.length() == 16) {
                          sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                      }
                      if (source.length() == 19) {
                          sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                      }
                      if (source.length() == 23) {
                          sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
                      }
                      date = sdf.parse((String) source);
                	}
                } catch (Exception e) {
                	e.printStackTrace();
                }
                return date;
            }
        };
    }
	
	//分页插件
	@Bean
    public PageHelper pageHelper(){
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("offsetAsPageNum","true");
        properties.setProperty("rowBoundsWithCount","true");
        properties.setProperty("reasonable","true");
        properties.setProperty("dialect","oracle");    //数据库的方言
        pageHelper.setProperties(properties);
        return pageHelper;
    }
	
	/**  
     * 文件上传配置  
     * @return  
     */  
    @Bean  
    public MultipartConfigElement multipartConfigElement() {  
        MultipartConfigFactory factory = new MultipartConfigFactory();  
        //单个文件最大  
        //factory.setMaxFileSize("5MB"); //KB,MB  
        /// 设置总上传数据总大小  
        //factory.setMaxRequestSize("100MB");
        
        //Springboot 2.X系列配置
        //文件最大10M,DataUnit提供5中类型B,KB,MB,GB,TB
        factory.setMaxFileSize(DataSize.of(5, DataUnit.MEGABYTES));
        /// 设置总上传数据总大小10M
        factory.setMaxRequestSize(DataSize.of(100, DataUnit.MEGABYTES));
        return factory.createMultipartConfig();  
    }  
	
	/**
	 * 打成war
	 */
	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
		return builder.sources(SpringBootApp.class);
	}

	public static void main(String[] args) {
		SpringApplication.run(SpringBootApp.class, args);
	}
	
}

